package top.jolyoulu.core.rdd.operator.transform

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

/**
 * @Author: JolyouLu
 * @Date: 2024/2/7 20:51
 * @Description
 */
object Spark017_RDD_Operator_AggregateByKey2 {
  def main(args: Array[String]): Unit = {
    //准备环境 [*]:表示使用当前系统最大核
    val sparkConf: SparkConf = new SparkConf().setMaster("local[*]").setAppName("RDD")
    val sc: SparkContext = new SparkContext(sparkConf)

    val rdd: RDD[(String, Int)] = sc.makeRDD(List(
      ("a", 5), ("a", 2), ("a", 2), ("a", 3),
      ("b", 5), ("b", 2), ("b", 2), ("b", 3)
    ),2)
    //计算字母出现次数的平均值
    //参数列表1: 初始值，用于在进行第一个key时将初始值传入与第一个做计算
    //参数列表2: 参数1分区内计算规则，参数2分区间计算规则
    val newRDD: RDD[(String, (Int, Int))] = rdd.aggregateByKey((0, 0))(
      (t, v) => {
        (t._1 + v, t._2 + 1) //数量相加，次数相加
      },
      (t1, t2) => {
        (t1._1 + t2._1, t1._2 + t2._2)
      }
    )
    //对map中的value转换
    val resultRDD: RDD[(String, Int)] = newRDD.mapValues({
      case (num, cnt) => {
        num / cnt
      }
    })
    resultRDD.collect().foreach(println)
    //关闭环境
    sc.stop()
  }

}
